#define DEBUG true

#include <SPI.h>

#include <DW1000.h>

#include "debug.h"
#include "def.h"
#include "i2c.h"
#include "arduino.h"

#define PIN_IRQ  2
#define PIN_RST  9
#define PIN_SS  SS

/* Edit anchorId */
// Each anchor must have a unique anchor ID (do not use ID 0)
const uint16_t anchorId = 2;
// UWB anchors and tags must have the same network ID
const uint16_t networkId = 0xDECA;
static uint8_t eui[] = {'A', 'C', 'K', 'D', 'A', 'T', 'R', 'X'};
// Sender of the last received frame in the S/W buffer
uint16_t sender;
// Counter part tag during two way ranging (PING, PONNG, RANGE, RANGEREPORT)
uint16_t tagCounterPart = ID_NONE;

// Current state of a UWB anchor state machine
char state = STATE_IDLE;
char i = 0;



// Last time that loop() is called
unsigned long curMillis;
// Last time that a frame is PUSHED INTO THE AIR FROM THE S/W BUFFER
unsigned long lastSent;
// Last time that a UWB device sends or receives a frame
// i.e., meaningful DWM1000 activity
unsigned long lastActivity;
unsigned long lastStateChange;

byte txBuffer[FRAME_LEN] = {0x41, 0x88, 0, 0xCA, 0xDE, 0x00, 0x00, 0x00, 0x00, 0x00};
byte rxBuffer[FRAME_LEN];

// Set to true if a frame is pushed into the air and SPI tx interrupt is triggered
boolean sentFrame = false;
// Set to true if a frame is received and SPI rx interrupt is triggered
// Not yet stored into the S/W buffer
boolean receivedFrame = false;


void updateState(int nextState) {
  state = nextState;
  lastStateChange = millis();
}

void noteActivity() {
  lastActivity = millis();
}



/********
 * Main *
 ********/
void setup() {
  #if DEBUG
  Serial.begin(115200);
  #endif // DEBUG
  

  PRINTLN(F("Setup finished"));
  PRINTLN(F("=============="));
  randomSeed(analogRead(0));
  state = STATE_IDLE;
}

void loop() {
    curMillis = millis();
  // Arduino didn't capture SPI tx/rx interrupts for more than RESET_TIMEOUT_MS
  // if (!sentFrame && !receivedFrame && curMillis - lastActivity > RESET_TIMEOUT_MS) {
    if (curMillis - lastActivity > RESET_TIMEOUT_MS) {
    for(i =0;i<9;i++){
      PRINT(txBuffer[i]);
    }
    PRINTLN(txBuffer[9]);
    noteActivity();
    return;
  }

  
}
